<template>
  <view style="position: relative; width: 100%;">
    <template v-if="readonly">
      <view
        class="focus-align-input readonly-input"
        @click="$emit('click')"
        :style="inputStyle"
      >
        <text :style="{ color: displayValue ? '#333' : '#bbb' , flex: 1, textAlign: 'right' }">
          {{ displayValue || placeholder }}
        </text>
        <slot />
      </view>
    </template>
    <template v-else>
      <u-input
        ref="uFormInput"
        v-model="inputValue"
        :placeholder="placeholder"
        :disabled="disabled"
        :clearable="clearable"
        @clear="handleClear"
        :input-align="isFocused ? 'left' : 'right'"
        :focus="isFocused"
        @focus="handleFocus"
        @blur="isFocused = false"
        :class="['focus-align-input', isFocused ? 'left-align' : '']"
        @input="onInput"
        :maxlength="maxInputLength"
        :required="required"
        :style="inputStyle"
        :type="type"
      />
      <slot />
    </template>
  </view>
</template>

<script>

import { Definition } from '../../engine/common/definition';

export default {
  name: 'FocusAlignInput',
  props: {
    modelValue: null,
    value: null, // 新增，兼容 :value 传参 只读模式下，传入的只读变量值
    placeholder: String,
    disabled: Boolean,
    maxLength: Number,
    required: {
      type: Boolean,
      default: false
    },
     // input 控件后面有其他控件时，input 框与其他控件间隔，默认44
    paddingRight: { 
      type:  Number,
      default: 40  // 默认值 44px
    },
     type: {
      type: String,
      default: 'text'
    },
     clearable: {
      type: Boolean,
      default: true // 默认显示清除按钮
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue','click'],
  data() {
    return {
      isFocused: false,
      inputValue: this.disabled
      ? (this.value ?? this.modelValue ?? " ")
      : (this.value ?? this.modelValue ? (this.value ?? this.modelValue).toString() : null)
    };
  },

  computed: {
     displayValue() {
       // 优先显示 inputValue，其次 value，其次 modelValue
       return this.inputValue ?? this.value ?? this.modelValue ?? '';      
    },
    maxInputLength() {
      return this.maxLength ?? Definition.maxTextLenForCommonTextfield;
    },

    // 是否后面跟有控件
hasSlotContent() {
  const slot = this.$slots.default && this.$slots.default();
  if (!slot) return false;
  // 过滤掉注释节点（type 为 Symbol(v-cmt)），空文本等
  return slot.some(vnode => {

   // console.log('---> hasSlotContent:' +  vnode.type);
    // 注释节点
    if (typeof vnode.type === 'symbol') return false;
    // 过滤空文本节点
    if (
      (typeof vnode.type === 'string' && vnode.type === 'text' && (!vnode.children || !vnode.children.toString().trim()))
    ) return false;
    // 其它节点（如 v-if 为 true 的组件/元素）返回 true
    return true;
  });
},

  // 后面跟有控件时保留一定控件
  // 注意：后面slot 没有内容的时候，padding 和有 slot 时 paddingRight 默认是一样的
  // 这样才能保障存文字和带有slot 图标的内容项中的文字一致
  // 如果slot 宽度太宽，传参自行调整 paddingRight 宽度
  inputStyle() {
    return {
      width: '100%',
      boxSizing: 'border-box',
      paddingRight: this.hasSlotContent ? this.paddingRight+'rpx' : '40rpx',
      //paddingRight: '60rpx'
      isFocused: false
    };
  }
  },
  watch: {
    modelValue(val) {
      this.inputValue = val;
    },
      inputValue(val) {
    this.$emit('update:modelValue', val);
  }
  },
  methods: {
    onInput(val) {
      this.$emit('update:modelValue', val);
    },
    // 实现 uView 表单协议
    focus() {
      this.$refs.uFormInput && this.$refs.uFormInput.focus && this.$refs.uFormInput.focus();
    },
    blur() {
      this.$refs.uFormInput && this.$refs.uFormInput.blur && this.$refs.uFormInput.blur();
    },

     handleFocus(event) {
        this.isFocused = true;
          // H5下可用
        this.$nextTick(() => {
              const input = this.$refs.uFormInput && this.$refs.uFormInput.$el.querySelector('input');
              if (input) input.select();
            });
        },

    handleClear() {
        this.inputValue = ''; // 清空本地值
        
         this.isFocused = false;
          this.$nextTick(() => {
            this.isFocused = true;
          });
    }        
  }
};
</script>

<style>
:deep(.focus-align-input.u-input) {
  border-bottom: none !important;
  box-shadow: none !important;
  background-image: none !important;
  position: relative !important;
}
:deep(.focus-align-input.left-align.u-input) {
  border-bottom: 2px solid #3c8dbc !important;
}
:deep(.focus-align-input .u-input__input) {
  text-align: right !important;
}
:deep(.focus-align-input.left-align .u-input__input) {
  text-align: left !important;
}
.readonly-input {
  min-height: 88rpx;
  display: flex;
  align-items: center;
  /*border-bottom: 1px solid #eee; */
  background: #ffffff;
  font-size: 28rpx;
  padding-left: 20rpx;
  cursor: pointer;
}
</style>